/**
 * Copyright (c) iwindplus Technologies Co., Ltd.2024-2030, All rights reserved.
 */

package com.iwindplus.mgt.server.service.system.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.cloud.nacos.NacosConfigManager;
import com.alibaba.nacos.api.config.ConfigType;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.iwindplus.base.domain.enums.BizCodeEnum;
import com.iwindplus.base.domain.enums.EnableStatusEnum;
import com.iwindplus.base.domain.exception.BizException;
import com.iwindplus.base.i18n.domain.constant.I18nConstant;
import com.iwindplus.mgt.domain.constant.MgtConstant.RedisCacheConstant;
import com.iwindplus.mgt.domain.dto.system.I18nMsgDTO;
import com.iwindplus.mgt.domain.dto.system.I18nMsgSearchDTO;
import com.iwindplus.mgt.domain.vo.system.I18nMsgPageVO;
import com.iwindplus.mgt.domain.vo.system.I18nMsgVO;
import com.iwindplus.mgt.server.dal.model.system.I18nMsgDO;
import com.iwindplus.mgt.server.dal.repository.system.I18nMsgRepository;
import com.iwindplus.mgt.server.service.system.I18nMsgService;
import jakarta.annotation.PostConstruct;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 国际化消息业务层接口实现类.
 *
 * @author zengdegui
 * @since 2020/3/25
 */

@Service
@CacheConfig(cacheNames = {RedisCacheConstant.CACHE_I18N_MSG})
@Slf4j
@Transactional(rollbackFor = Exception.class)
@RequiredArgsConstructor
public class I18nMsgServiceImpl implements I18nMsgService {

    private final Optional<NacosConfigManager> nacosConfigManagerOpt;
    private final I18nMsgRepository i18nMsgRepository;

    @CacheEvict(allEntries = true)
    @Override
    public boolean save(I18nMsgDTO entity) {
        entity.setStatus(EnableStatusEnum.ENABLE);
        entity.setBuildInFlag(Boolean.FALSE);
        this.i18nMsgRepository.getNameIsExist(entity.getName());
        this.i18nMsgRepository.getFileNameIsExist(entity.getFileName());
        entity.setSeq(this.i18nMsgRepository.getNextSeq());
        final I18nMsgDO model = BeanUtil.copyProperties(entity, I18nMsgDO.class);
        this.i18nMsgRepository.save(model);
        entity.setId(model.getId());
        this.pushData(model.getFileName(), model.getContent());
        return Boolean.TRUE;
    }

    @CacheEvict(allEntries = true)
    @Override
    public boolean removeByIds(List<Long> ids) {
        List<I18nMsgDO> list = this.i18nMsgRepository.listByIds(ids);
        if (CollUtil.isEmpty(list)) {
            throw new BizException(BizCodeEnum.DATA_NOT_EXIST);
        }
        boolean match = list.stream().filter(Objects::nonNull).anyMatch(I18nMsgDO::getBuildInFlag);
        if (Boolean.TRUE.equals(match)) {
            throw new BizException(BizCodeEnum.HAS_BUILD_IN_DATA);
        }
        this.i18nMsgRepository.removeByIds(ids);

        list.parallelStream().forEach(item -> this.removeData(item.getFileName()));
        return Boolean.TRUE;
    }

    @CacheEvict(allEntries = true)
    @Override
    public boolean edit(I18nMsgDTO entity) {
        I18nMsgDO data = this.i18nMsgRepository.getById(entity.getId());
        if (Objects.isNull(data)) {
            throw new BizException(BizCodeEnum.DATA_NOT_EXIST);
        }
        if (Boolean.TRUE.equals(data.getBuildInFlag())) {
            throw new BizException(BizCodeEnum.BUILD_IN_DATA_NOT_OPERATE);
        }
        if (CharSequenceUtil.isNotBlank(entity.getName()) && !CharSequenceUtil.equals(data.getName(), entity.getName().trim())) {
            this.i18nMsgRepository.getNameIsExist(entity.getName().trim());
        }
        if (CharSequenceUtil.isNotBlank(entity.getFileName()) && !CharSequenceUtil.equals(data.getFileName(), entity.getFileName().trim())) {
            this.i18nMsgRepository.getFileNameIsExist(entity.getFileName().trim());
        }
        if (Objects.isNull(entity.getVersion())) {
            entity.setVersion(data.getVersion());
        }
        final I18nMsgDO model = BeanUtil.copyProperties(entity, I18nMsgDO.class);
        this.i18nMsgRepository.updateById(model);
        this.pushData(model.getFileName(), model.getContent());
        return Boolean.TRUE;
    }

    @CacheEvict(allEntries = true)
    @Override
    public boolean editStatus(Long id, EnableStatusEnum status) {
        I18nMsgDO data = this.i18nMsgRepository.getById(id);
        if (Objects.isNull(data)) {
            throw new BizException(BizCodeEnum.DATA_NOT_EXIST);
        }
        if (Boolean.TRUE.equals(data.getBuildInFlag())) {
            throw new BizException(BizCodeEnum.BUILD_IN_DATA_NOT_OPERATE);
        }
        if (status.equals(data.getStatus())) {
            throw new BizException(BizCodeEnum.ALREADY_OPERATED);
        }
        I18nMsgDO param = new I18nMsgDO();
        param.setId(id);
        param.setStatus(status);
        param.setVersion(data.getVersion());
        this.i18nMsgRepository.updateById(param);
        this.pushData(data.getFileName(), data.getContent());
        return Boolean.TRUE;
    }

    @CacheEvict(allEntries = true)
    @Override
    public boolean editBuildIn(Long id, Boolean buildInFlag) {
        I18nMsgDO data = this.i18nMsgRepository.getById(id);
        if (Objects.isNull(data)) {
            throw new BizException(BizCodeEnum.DATA_NOT_EXIST);
        }
        if (buildInFlag.equals(data.getBuildInFlag())) {
            throw new BizException(BizCodeEnum.ALREADY_OPERATED);
        }
        I18nMsgDO param = new I18nMsgDO();
        param.setId(id);
        param.setBuildInFlag(buildInFlag);
        param.setVersion(data.getVersion());
        this.i18nMsgRepository.updateById(param);
        return Boolean.TRUE;
    }

    @Override
    public IPage<I18nMsgPageVO> page(I18nMsgSearchDTO entity) {
        PageDTO<I18nMsgDO> page = new PageDTO<>(entity.getCurrent(), entity.getSize());
        page.setOptimizeCountSql(Boolean.FALSE);
        page.setOptimizeJoinOfCountSql(Boolean.FALSE);
        LambdaQueryWrapper<I18nMsgDO> queryWrapper = Wrappers.lambdaQuery(I18nMsgDO.class)
            .orderByDesc(I18nMsgDO::getModifiedTime);
        if (Objects.nonNull(entity.getStatus())) {
            queryWrapper.eq(I18nMsgDO::getStatus, entity.getStatus());
        }
        if (CharSequenceUtil.isNotBlank(entity.getName())) {
            queryWrapper.eq(I18nMsgDO::getName, entity.getName().trim());
        }
        if (CharSequenceUtil.isNotBlank(entity.getFileName())) {
            queryWrapper.like(I18nMsgDO::getFileName, entity.getFileName().trim());
        }
        if (CharSequenceUtil.isNotBlank(entity.getContent())) {
            queryWrapper.like(I18nMsgDO::getContent, entity.getContent().trim());
        }
        queryWrapper.select(I18nMsgDO::getId, I18nMsgDO::getCreatedTime, I18nMsgDO::getCreatedTimestamp, I18nMsgDO::getCreatedBy,
            I18nMsgDO::getModifiedTime, I18nMsgDO::getModifiedTimestamp, I18nMsgDO::getModifiedBy, I18nMsgDO::getVersion, I18nMsgDO::getStatus,
            I18nMsgDO::getName, I18nMsgDO::getFileName, I18nMsgDO::getSeq, I18nMsgDO::getBuildInFlag
        );
        final PageDTO<I18nMsgDO> modelPage = this.i18nMsgRepository.page(page, queryWrapper);
        return modelPage.convert(model -> BeanUtil.copyProperties(model, I18nMsgPageVO.class));
    }

    @Cacheable(key = "#root.methodName + '_' + #p0", condition = "#p0 != null", unless = "#result == null")
    @Override
    public I18nMsgVO getDetail(Long id) {
        I18nMsgDO data = this.i18nMsgRepository.getById(id);
        if (Objects.isNull(data)) {
            throw new BizException(BizCodeEnum.DATA_NOT_EXIST);
        }
        I18nMsgVO result = BeanUtil.copyProperties(data, I18nMsgVO.class);
        return result;
    }

    @PostConstruct
    private void sendMsg() {
        final List<I18nMsgDO> list = this.i18nMsgRepository.list(Wrappers.lambdaQuery(I18nMsgDO.class)
            .eq(I18nMsgDO::getStatus, EnableStatusEnum.ENABLE));
        if (ObjectUtil.isEmpty(list)) {
            return;
        }

        list.parallelStream().forEach(data -> {
            String dataId = data.getFileName();

            this.pushData(dataId, data.getContent());
        });
    }

    private void pushData(String fileName, String content) {
        if (nacosConfigManagerOpt.isEmpty()) {
            log.warn("NacosConfigManager not present, skip route push");
            return;
        }
        NacosConfigManager nacosConfigManager = nacosConfigManagerOpt.get();

        String dataId = fileName.endsWith(I18nConstant.FILE_SUFFIX) ? fileName : fileName + I18nConstant.FILE_SUFFIX;
        try {
            boolean ok = nacosConfigManager.getConfigService().publishConfig(
                dataId, I18nConstant.I18N_GROUP, content, ConfigType.PROPERTIES.getType());
            if (!ok) {
                log.info("推送国际化文件={}，到 Nacos 失败", dataId);
            } else {
                log.info("推送国际化文件={}，到 Nacos 成功", dataId);
            }
        } catch (Exception ex) {
            log.error("推送国际化文件文件={}，到 Nacos Exception={}", dataId, ex);
        }
    }

    private void removeData(String fileName) {
        if (nacosConfigManagerOpt.isEmpty()) {
            log.warn("NacosConfigManager not present, skip route push");
            return;
        }
        NacosConfigManager nacosConfigManager = nacosConfigManagerOpt.get();

        String dataId = fileName.endsWith(I18nConstant.FILE_SUFFIX) ? fileName : fileName + I18nConstant.FILE_SUFFIX;
        try {
            boolean ok = nacosConfigManager.getConfigService().removeConfig(dataId, I18nConstant.I18N_GROUP);
            if (!ok) {
                log.info("删除 Nacos 国际化文件={}，失败", dataId);
            } else {
                log.info("删除 Nacos 国际化文件={}，成功", dataId);
            }
        } catch (Exception ex) {
            log.error("删除 Nacos 国际化文件={}， Exception={}", dataId, ex);
        }
    }
}
